package com.topboya.linker.ui.activity;

import android.content.Context;
import android.content.pm.ActivityInfo;
import android.media.AudioManager;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.topboya.linker.R;
import com.topboya.linker.ui.base.Presenter.BasePresenter;
import com.topboya.linker.ui.base.activity.BaseActivity;
import com.topboya.linker.utils.LogUtils;

//资料详情h5页面
public class FileDetailWebActivity extends BaseActivity {

    private static final String TAG = "FileDetailWebActivity:";
    private TextView toolbar_title;
    private TextView tv_toolbar_right;
    private WebView web_fifedetail;
    private String URL ="http://otc.topboya.com/share/appH5/index.html?id=";
    private String fifeid ;
    //添加一下代码解决问题 webView退出之后音频视频还在播放问题
    private AudioManager audioManager;
    private AudioManager.OnAudioFocusChangeListener listener;
    private FrameLayout fullVideo;
    private Toolbar toolbar;
    private View customView;

    @Override
    protected int getLayoutId() {

        return R.layout.activity_filedetail_web;
    }

    @Override
    protected void initView() {

        toolbar_title = findViewById(R.id.toolbar_title);
        web_fifedetail = findViewById(R.id.web_fifedetail);
        tv_toolbar_right = findViewById(R.id.tv_toolbar_right);
        fullVideo = findViewById(R.id.full_video);
        toolbar = findViewById(R.id.toolbar);
    }

    @Override
    protected void initData() {

         initTitlebar();
         fifeid = getIntent().getStringExtra("fifeID");
        LogUtils.v(TAG + "URL+fifeid:"+URL+fifeid);
        web_fifedetail.setWebChromeClient(new MyWebChromeClient());
        // 设置WebView的客户端,不设置网页会跳转到手机浏览器
        web_fifedetail.setWebViewClient(new MyWebViewClient());
         webvewSetting();
        web_fifedetail.loadUrl(URL+fifeid);
        web_fifedetail.addJavascriptInterface(new JavaScriptinterface(this),"Android");
    }
    public class JavaScriptinterface {
        Context context;
        public JavaScriptinterface(Context c) {
            context= c;
        }

        /**
         * 与js交互时用到的方法，在js里直接调用的
         */
        @JavascriptInterface
        public void changeAppLocal(String ishide) {

            runOnUiThread(new Thread(){
                @Override
                public void run() {

                    if (ishide.equals("hide")){

                        toolbar.setVisibility(View.GONE);
                    }else {

                        toolbar.setVisibility(View.VISIBLE);

                    }
                }
            });


        }
    }
    private void webvewSetting() {

        WebSettings webSettings = web_fifedetail.getSettings();
        // 让WebView能够执行javaScript
        webSettings.setJavaScriptEnabled(true);
        // 让JavaScript可以自动打开windows
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setUseWideViewPort(true); // 关键点 全屏播放視頻
        // 设置缓存
        webSettings.setAppCacheEnabled(true);
        // 设置缓存模式,一共有四种模式
        webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        // 设置缓存路径
//        webSettings.setAppCachePath("");
        // 支持缩放(适配到当前屏幕)
        webSettings.setSupportZoom(true);
        // 将图片调整到合适的大小
        webSettings.setUseWideViewPort(true);
        // 支持内容重新布局,一共有四种方式
        // 默认的是NARROW_COLUMNS
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        // 设置可以被显示的屏幕控制
        webSettings.setDisplayZoomControls(true);
        // 设置默认字体大小
        webSettings.setDefaultFontSize(12);
    }

    private void initTitlebar() {

        toolbar.setVisibility(View.VISIBLE);
        toolbar_title.setText("资料");
        tv_toolbar_right.setVisibility(View.GONE);

    }
    @Override
    protected void initListener() {

        toolbar.setNavigationOnClickListener(v -> finish());


    }

    @Override
    protected BasePresenter createPresenter() { return null; }

    @Override
    protected void onResume() {

        if (audioManager!= null) {
            audioManager.abandonAudioFocus(listener);
            audioManager = null;
        }
        super.onResume();
    }
    @Override
    protected void onPause() {

        audioManager = (AudioManager)getSystemService(AUDIO_SERVICE);
        listener = focusChange -> {};
        int result = audioManager.requestAudioFocus(listener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
        if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) { }
        super.onPause();
    }
   private class MyWebViewClient extends WebViewClient{

       @Override
       public boolean shouldOverrideUrlLoading(WebView view, String url) {

           String script=String.format("javascript:changeAppLocal()");
           view.loadUrl(url);
           web_fifedetail.evaluateJavascript(script, value -> LogUtils.v(TAG + "script:"+value));
           return true;// 返回false
       }
   }
    private class MyWebChromeClient extends WebChromeClient{

        @Override
        public void onHideCustomView() {
            //退出全屏
            if (customView == null){
                return;
            }
            //移除全屏视图并隐藏
            fullVideo.removeView(customView);
            toolbar.setVisibility(View.VISIBLE);
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//设置竖屏
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);//清除全屏

        }

        @Override
        public void onShowCustomView(View view, CustomViewCallback callback) {
            //进入全屏
            customView = view;
            toolbar.setVisibility(View.GONE);
            fullVideo.addView(customView);
            fullVideo.bringToFront();
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);//设置横屏
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);//设置全屏
        }
    }
}
